<?php


namespace app\admin\controller;


use app\admin\model\AdminLoginLog;
use think\Controller;
use think\Db;
use think\Request;
use think\Validate;

class Pub extends Controller {


    private $loginLogModel;
    public function initialize()
    {
        parent::initialize();
        $this->loginLogModel = new AdminLoginLog();
    }

    // 管理员登录
    public function login(Request $request){
        if($request->isPost()){

            $params = $request->post();

            $rule = [
                'username|账户'=>'require',
                'password|密码'=>'require',
                'verification_code|验证码'=>'require',
            ];

            $message = [
                'require'=>'不能为空',
            ];

            //验证
            $validator = Validate::make($rule, $message);
            if(!$validator->check($params)){
                $res['err'] = 1001;
                $res['msg'] = $validator->getError();
                return response($res,200,[],'json');
            }

            //校验验证码
            if(!captcha_check($params['verification_code'])){
                $res['err'] = 1002;
                $res['msg'] = '验证码错误';
                return response($res,200,[],'json');
            }
            $type = 'username';
            $username = trim($params['username']);
            // 是否是邮箱登录
            if(filter_var($username, FILTER_VALIDATE_EMAIL)){
                //是邮箱
                $userMap['is_del'] = 0;
                $userMap['email'] = $username;
                $type = 'email';
                $user = Db::table('admin_user')->where($userMap)->find();
            }
            //手机号登录
            if(preg_match("/^1[3-9][0-9]\d{8}$/",$username)){

                $userMap['is_del'] = 0;
                $userMap['mobile'] = $username;
                $type = 'mobile';
                $user = Db::table('admin_user')->where($userMap)->find();
            }
            // 用户名
            if($type==='username') {
                // 用户名登录
                $userMap['is_del'] = 0;
                $userMap['username'] = trim($params['username']);
                $user = Db::table('admin_user')->where($userMap)->find();
            }

            if($user==null){
                $res['err'] = 1003;
                $res['msg'] = '该账号不存在';
                return response($res,200,[],'json');
            }

            // 是否被禁用
            if($user['status']==2){
                $res['err'] = 1004;
                $res['msg'] = '该账号已经被禁用,请联系管理员';
                return response($res,200,[],'json');
            }

            // 检测密码是否正确
            $inputPass = md5(trim($params['password']).$user['salt']);
            if($inputPass!==$user['password']){
                $res['err'] = 1005;
                $res['msg'] = '您输入的密码错误请重试';
                return response($res,200,[],'json');
            }

            $user['role_name'] = Db::table('admin_role')->where('role_id','=',$user['role_id'])->value('role_name');
            unset($user['password']);
            session('user',$user);

            //写入日志
            $logData['admin_id'] = $user['admin_id'];
            $logData['username'] = $user['username'];
            $logData['role_name'] = $user['role_name'];
            $logData['ip'] = $ip =  $request->ip();
            if($ip=='127.0.0.1'){
                $logData['address'] = '本地地址';
            } else {
                $ipLocation = new \IpLocation();
                $ipAddr = $ipLocation->getlocation($ip);
                $logData['address'] = $ipAddr['country'].','.$ipAddr['area'];
            }
            $logData['type'] = 1;
            $logId = $this->loginLogModel->writeLog($logData);

            if($logId) {
                $res['err'] = 0;
                $res['msg'] = '登陆成功';
                $res['goUrl'] = url('/admin/index/index');
                return response($res, 200, [], 'json');
            } else {
                $res['err'] = 1006;
                $res['msg'] = '登陆失败,登录日志写入失败';
                return response($res, 200, [], 'json');
            }

        } else {

            return view();
        }

    }



    // 退出系统
    public function logout(Request $request){

        $user = session('user');
        //写入日志
        $logData['admin_id'] = $user['admin_id'];
        $logData['username'] = $user['username'];
        $logData['role_name'] = $user['role_name'];
        $logData['type'] = 2;
        $logData['ip'] = $ip = $request->ip();

        if($ip=='127.0.0.1'){
            $logData['address'] = '本地地址';
        } else {
            $ipLocation = new \IpLocation();
            $ipAddr = $ipLocation->getlocation($ip);
            $logData['address'] = $ipAddr['country'].','.$ipAddr['area'];
        }

        $logId = $this->loginLogModel->writeLog($logData);
        session('user',null);

        if($logId) {

            return redirect(url('/admin/pub/login'));
        } else {

            $this->error('退出系统失败');
        }

    }


}